package controller;

import com.google.gson.Gson;
import pojo.WorkOrder;
import service.IWorkorderService;
import service.impl.WorkOrderServiceImpl;
import util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

@WebServlet("/wo/*")
public class WorkOrderController extends HttpServlet {
    private IWorkorderService iws=new WorkOrderServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        int index = requestURI.lastIndexOf("/") + 1;
        String mName = requestURI.substring(index);
        if (mName.length() == 0) {
            mName = "showdt";
        }
        Class cla = this.getClass();
        Method method = null;
        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String executor= request.getParameter("executor");
        String description=request.getParameter("description");
        Integer orderlevel=Integer.parseInt(request.getParameter("orderlevel"));
        Integer pid=Integer.parseInt(request.getParameter("pid"));

        WorkOrder wo=new WorkOrder(pid,executor,description,orderlevel,new Date());
        boolean b=iws.addWorkOrder(wo);
        response.getWriter().println(new Gson().toJson(b));
    }
    public void getListByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        PageHelper ph=new PageHelper();
        int indexpage=Integer.parseInt(request.getParameter("indexpage"));
        ph.setPageIndex(indexpage);
        ph.setDateCount(iws.queryPageDataCount());
        ph.setListIndex(iws.queryIndexData(ph));

        response.getWriter().println(new Gson().toJson(ph));

    }
}
